package com.sky.wsp.mybatis.plus.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.sky.wsp.mybatis.plus.utils.SecurityContextHolder;
import com.sky.wsp.mybatis.plus.config.properties.TenantProperties;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.List;

/**
 * 多租户处理类
 *
 * @author wangshaopeng@talkweb.com.cn
 * @Date 2023-01-11
 */
public class MultiTenantHandler implements TenantLineHandler {

    private final TenantProperties properties;

    public MultiTenantHandler(TenantProperties properties) {
        this.properties = properties;
    }

    @Override
    public Expression getTenantId() {
        Long tenantId = SecurityContextHolder.getTenantId();
        return new LongValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return properties.getColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {

        //忽略指定用户对租户的数据过滤
//        List<String> ignoreLoginNames=properties.getIgnoreLoginNames();
//        String loginName=SecurityContextHolder.getUsername();
//        if(null!=ignoreLoginNames && ignoreLoginNames.contains(loginName)){
//            return true;
//        }

        //忽略指定表对租户数据的过滤
        List<String> ignoreTables = properties.getIgnoreTables();
        if (null != ignoreTables && ignoreTables.contains(tableName)) {
            return true;
        }

        //需要进行租户数据过滤的表，没有匹配上则不加租户过滤条件
//        List<String> filterTables = properties.getFilterTables();
//        if (null != filterTables && !filterTables.contains(tableName)) {
//            return true;
//        }
        return false;
    }
}
